package com.yonyou.pmclouds.mob.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.condition.PublicDeployCondition;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.exception.IllegalRequestArgException;
import com.yonyou.pmclouds.basecom.util.RSAUtil;
import com.yonyou.pmclouds.experuser.entity.ExperUserVO;
import com.yonyou.pmclouds.experuser.rmiitf.ExperUserRemoteMobService;
import com.yonyou.pmclouds.mobreg.entity.MobRegVO;
import com.yonyou.yht.sdk.UserCenter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Controller
@Conditional(PublicDeployCondition.class)
@RequestMapping(value="/mobile/mobReg")
public class MobRegisterController {
	
	private ObjectMapper objectMapper = new ObjectMapper();
	
	@Reference(version = ApplicationConsts.APPLICATION_VERSION)
	private ExperUserRemoteMobService experUserRemoteMobService;
	
	@RequestMapping(value="/userRegCheck")
	@ResponseBody
	public Object userRegCheck(String userMobile) throws BusinessException{
		
		//判断用户是否已经注册
		String checkResult = UserCenter.isUserExist(userMobile);
		
		Map checkResultMap = null;
		try {
			checkResultMap = objectMapper.readValue(checkResult, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		
		if(Integer.valueOf(0).equals(checkResultMap.get("status"))){
			log.error("请求友户通接口异常，具体信息为：" + checkResultMap.get("msg"));
			return false;
		}else if(!Integer.valueOf(0).equals(checkResultMap.get("flag"))){
			log.error("用户已存在，具体信息为：" + checkResultMap.get("msg"));
			return false;
		}
		
		return true;
	}
	
	@RequestMapping(value="/sendPhoneCode")
	@ResponseBody
	public Object sendPhoneCode(@RequestParam String userMobile, @RequestParam String picCode, @RequestParam String picKey) {

		String sendCodeResult = UserCenter.sendcode(userMobile, "mobile", picKey, picCode);
		Map sendResultMap = null;
		try {
			sendResultMap = objectMapper.readValue(sendCodeResult, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(Integer.valueOf(0).equals(sendResultMap.get("status"))){
			log.error("发送手机验证码出错，具体信息为：" + sendResultMap.get("msg"));
			return false;
		}
		return true;
	}
	
	/**
	 * 
	 * 方法功能描述：验证码校验。
	 * 
	 * <b>参数说明</b>
	 * @param userMobile
	 * @param verifyCode
	 * @throws BusinessException
	 * @author zhangwce
	 * @time 2018年1月22日 下午2:47:25
	 */
	@RequestMapping(value="/validateCode")
	@ResponseBody
	public Object validateCode(String userMobile,String verifyCode) throws BusinessException{
		
		String validateResult = UserCenter.validateCode(userMobile, "mobile", verifyCode);
		
		Map validateResultMap = null;
		try {
			validateResultMap = objectMapper.readValue(validateResult, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if(Integer.valueOf(0).equals(validateResultMap.get("status"))){
			log.error("验证码校验错误，具体信息为：" + validateResultMap.get("msg"));
			return false;
		}
		
		return true;
	}
	
	
	@RequestMapping(value="/mobRegister")
	@ResponseBody
	public Object mobRegister(@RequestBody @Validated MobRegVO mobRegInfo,BindingResult errors) throws BusinessException{

		if (errors.hasErrors()) {
			throw new IllegalRequestArgException();
		}

		// 用户注册
		String userId = experUserRegister(mobRegInfo);
//		String userInfo = UserCenter.getUserByContact(mobRegInfo.getUserMobile(), "mobile");
//		
//		Map userResultMap = null;
//		try {
//			userResultMap = objectMapper.readValue(userInfo, Map.class);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		String userId = (String)((List<Map>)userResultMap.get("users")).get(0).get("userId");
		
		if(userId == null || "".equals(userId)){
			log.error("未获取到注册用户的ID");
			throw new BusinessException("用户注册出错");
		}
		
		//String userId = "fe2a6542-9299-4849-a88c-7979c63018f0";
		// 将体验用户信息保存到本地
//		saveExperUserToLocal(mobRegInfo, userId);
		
		return true;
	}
	/**
	 * 
	 * 方法功能描述：保存体验用户信息。
	 * 
	 * <b>参数说明</b>
	 * @param mobRegInfo
	 * @param userId
	 * @throws BusinessException
	 * @author zhangwce
	 * @time 2018年1月22日 下午2:59:46
	 */
	private void saveExperUserToLocal(MobRegVO mobRegInfo, String userId) throws BusinessException {
		ExperUserVO experUserVO = new ExperUserVO();
		experUserVO.setUserid(userId);
		experUserVO.setUser_name(mobRegInfo.getUserName());
		experUserVO.setMobile(mobRegInfo.getUserMobile());
		
		experUserRemoteMobService.addExperUser(experUserVO);
	}

	/**
	 * 
	 * 方法功能描述：调用友户通接口注册体验用户。
	 * 
	 * <b>参数说明</b>
	 * @param mobRegInfo
	 * @return
	 * @throws BusinessException
	 * @author zhangwce
	 * @time 2018年1月22日 下午3:00:40
	 */
	private String experUserRegister(MobRegVO mobRegInfo) throws BusinessException {
		Map<String,String> userMap = new HashMap<String, String>();

		userMap.put("userName", mobRegInfo.getUserName());
		userMap.put("userMobile", mobRegInfo.getUserMobile().replaceAll("%2B", "+"));
		userMap.put("userPassword", RSAUtil.decrypt(mobRegInfo.getUserPassword().replaceAll("%2B", "+")));

		String regResult = UserCenter.addCloudUser(userMap);

		if(StringUtils.isEmpty(regResult))
			throw new BusinessException("用户注册失败：友户通服务异常");
		
		Map regResultMap = new HashMap();
		try {
			regResultMap = objectMapper.readValue(regResult, Map.class);
		} catch (Exception e) {
			log.error("json转换出错，错误信息为："+e.getMessage());
		} 
		
		if(Integer.valueOf(0).equals(regResultMap.get("status"))){
			String msg = (String)regResultMap.get("msg");
			log.error("用户注册失败，错误信息为："+msg);
			throw new BusinessException(msg);		
		}
		
		// 获取注册后返回的用户ID
		String userId = ((Map) regResultMap.get("user")).get("userId") == null ? ""
				: (String) ((Map) regResultMap.get("user")).get("userId");
		return userId;
	}

	
}
